﻿<?php
require_once( ROOT_UTIL_CLASS. 'Util.class.php');
?>

<?php
class DataObject extends DataObjectUtils {
	var $className = "DataObject";
	var $id;
	var $attributes;

	function add( $name, $value ){
	//echo "(".$value.")";
		$this->attributes[$name] = array('name'=>$name, 'data'=>$value);
	}
	
	// Gera um outro objeto baseado na instância usada para gerar o clone.
	function xgetNewInstance(){
		echo "pegou(".$this->id .")";
		$newObject = new DataObject($this->id, $this->attributes);
		$newObject->reset();
		return $newObject;
	}
	// Adiciona atributos ao objeto DO.
	// Recebe um array contendo os dados para o atributo.
	function addAttribute( $attribute ){
		$attributes[] = $attribute;
	}
	function load(){
		return new PeriodoDO();
	}
	function test(){
		echo "Criou";
	}
	function DataObject($id = "", $attributes = ""){
		$this->id 			= $id;
		$this->attributes	= $attributes;
	}
	function reset(){
		foreach ( $this->attributes as $name => $value ) {
			$this->attributes[$name]["data"] = "NULL";
		}
	}
}

/*
 *
 * Classe responsável por gornecer utilitários para manipulação dos objetos DATA.
 *
 */
class DataObjectUtils extends Kernel {
	var $className = "DataObjectUtils";

	function getTable(){
		return $this->table;
	}
	function getColumnName( $attribute ){
		return $this->attributes[$attribute]["name"];
	}
	function set($attribute, $value){
		$this->attributes[$attribute]["data"] = $value;
	}
	function get($attribute){
		return $this->attributes[$attribute]["data"];
	}
	function getDataJSON($attribute, $name = ''){
		if ( $name == "" ){
			return $attribute . " : '" . $this->prepareData( $this->attributes[$attribute]["data"] ) . "'";
		} else {
			return $name . " : '" . $this->prepareData( $this->attributes[$attribute]["data"] ) . "'";
		}
	}
	function showAttributes(){
		$class_vars = get_class_vars(get_class($this));
		foreach ($class_vars as $name => $value) {
		    echo "$name : $value<br>";
		}
	}
	function formatAttributesForSqlQuery(){
		// Instancia a Classe Sql para utilizar o método de formatação de colunas para query.
		// (Importante) Para utilizar esse método é necessário instanciar a Classe Sql.
		$sql = new Sql();
		$fields = "";
		$aux = "";
		foreach ( $this->attributes as $name => $value ) {
			//if ( $this->attributes[$name]["data"] != "NULL" ){
				$fields .= $aux . $sql->formatFieldToSqlQuery( $this->attributes[$name]["type"], $this->attributes[$name]["name"] );
				$aux = ", ";
			//}
		}
		return $fields;
	}
	function transformDataObjectToJSON( $fields = "" ){
		$stb = new StringBuffer();
		$stb->append("{");
		$aux = "";
		foreach ( $this->attributes as $name => $value ) {
			if ( $fields == "" ){
				$stb->append($aux ."'".$this->attributes[$name]["name"] . "':'" . $this->prepareData( $this->attributes[$name]["data"] ) . "'");
			} else {
				$arrFields = explode(",", $fields);
				for ( $i = 0; $i < count($arrFields); $i++ ) { 
					if ( trim( $arrFields[$i] ) == $name ){
						$stb->append($aux . "'".$this->attributes[$name]["name"] . "':'" . $this->prepareData( $this->attributes[$name]["data"] ) . "'");
					}
				}
			}
			$aux = ",";
		}
		$stb->append("}");
		return $stb->toString();
	}
	function prepareData( $data ){
		$data = str_replace( "\n", "\\n", $data);
		$data = str_replace( "'", "\\'", $data);
		//return utf8_encode( $data );
		return $data ;
	}

	function loadDataObjectByPost( $p_data, $decode = FALSE ){
		return $this->loadDataObject( $p_data, $decode  );
	}
	function loadDataObjectByQueryString( $p_data, $decode = FALSE ){
		return $this->loadDataObject( $p_data, $decode  );
	}
	function loadDataObjectByResultSet( $p_data, $decode = FALSE ){
		return $this->loadDataObject( $p_data, $decode );
	}
	function loadDataObject( $p_object, $decode = FALSE ){
	//	$stb = new StringBuffer();
	//	$stb->append("<table border><tr><td>Key</td><td>Value</td></tr>");
		foreach ( $this->attributes as $key => $value ) { 
			
			//echo $this->attributes[$key]["name"];
			$data = "NULL";
			if ( isset($p_object[ $this->attributes[$key]["name"] ]) ){
				$data = $p_object[ $this->attributes[$key]["name"] ];
			} else if ( isset($p_object[ $this->table ."_". $this->attributes[$key]["name"] ]) ){
				$data = $p_object[ $this->table ."_". $this->attributes[$key]["name"] ];
			}
			if ( $data != "NULL" ){
			//	$stb->append("<tr><td>".$key."</td><td>".$p_object[ $this->attributes[$key]["name"] ]."</td></tr>");
				if ( $decode ){
						$this->set($key, utf8_decode($data) );
					} else {
						$this->set($key, utf8_decode($data) );
					}
			}
		} 
		//$stb->append("</table>");
		//$this->setLog("debug", "LOAD_DO", $stb->toString());

		return $this;
	}

	function generateDataObject( $instanceDB, $table ){
		$commandSql = "SELECT * FROM " . $table;
		
		$sql = new Sql();
		$result = $sql->executeQuery($instanceDB, $commandSql);
		if ( $result ){
			echo "<pre>";
		echo "
		class ".$table."DO extends DataObjectUtils {
			var \$table = \"".$table."\";
			var \$attributes = array(\n";
			$fields = mysql_num_fields($result);
			$rows   = mysql_num_rows($result);
			$table  = mysql_field_table($result, 0);
			for ($i=0; $i < $fields; $i++) {
				$type  = mysql_field_type($result, $i);
				$name  = mysql_field_name($result, $i);
				$len   = mysql_field_len($result, $i);
				$flags = mysql_field_flags($result, $i);

		echo "				\"" . $name . "\"=> array(\"name\" => \"" . $name . "\",\"key\" => \"" . ((strpos($flags, "primary_key")!==false)?"true":"false") . "\", \"type\" => \"".$type."\", \"length\" => \"" . $len . "\", \"null\" => \"" . ((strpos($flags, "not_null")!==false)?"NO":"YES") . "\", \"values\" => \"\", \"default\" => \"0\", \"label\" => \"Codigo\", \"data\" => \"NULL\"),\r\n";
 
			}
			
		echo "
			);
			function getNewInstance(){
				return new ".$table."DO();
			}
		}";
			echo "</pre>";
		}
	}
	
}
?>